package com.wjk.kylin.modules.system.schedule.entity;

import com.baomidou.mybatisplus.annotation.*;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.wjk.kylin.core.common.entity.BaseEntity;
import com.wjk.kylin.core.common.valid.insert;
import com.wjk.kylin.core.common.valid.update;
import com.wjk.kylin.core.constant.ScheduleConstants;
import com.wjk.kylin.core.job.ScheduleUtils;
import lombok.Data;
import lombok.ToString;
import org.apache.commons.lang3.StringUtils;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import java.util.Date;

/**
 * <p>
 * 定时任务表
 * </p>
 *
 * @author wangjkui
 * @since 2020-06-04
 */
@Data
@ToString
@TableName("sys_schedule")
public class Schedule extends BaseEntity<Schedule> {

    /**
     * 任务名
     */
    @NotBlank(message = "任务名称不能为空",groups = {insert.class})
    @Size(min = 0, max = 64, message = "任务名称不能超过64个字符",groups = {insert.class, update.class})
    @TableField("job_name")
    private String jobName;

    /**
     * 任务组
     */
    @TableField("job_group")
    @NotBlank(message = "任务组不能为空",groups = {insert.class, update.class})
    private String jobGroup;

    /**
     * 启用状态（0：启用；1：暂停）
     */
    @TableField("status")
    @Pattern(regexp="^[0-1]",message = "状态只能为0或1",groups = {insert.class, update.class})
    private String status;


    /** 调用目标 spring bean名称 */
    @NotBlank(message="调用目标不能为空",groups = {insert.class})
    @Size(min = 0, max = 1000, message = "调用目标字符串长度不能超过500个字符",groups = {insert.class, update.class})
    @TableField("bean_name")
    private String beanName;

    /** 调用目标参数 */
    @TableField("params")
    private String params;

    /** cron执行表达式 */
    @NotBlank(message = "Cron执行表达式不能为空",groups = {insert.class})
    @Size(min = 0, max = 255, message = "Cron执行表达式不能超过255个字符",groups = {insert.class, update.class})
    @TableField("cron_expression")
    private String cronExpression;

    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    public Date getNextValidTime(){
        if (StringUtils.isNotBlank(cronExpression)){
            return ScheduleUtils.getNextExecution(cronExpression);
        }
        return null;
    }

}
